﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
using Vit.Web.Mvc.DataAnnotations;

namespace Vit.Web.Extensions
{
	public static class ModelMetadataExtensions
	{
		public static bool ShowForGrid(this ModelMetadata metadata)
		{
			if (metadata.AdditionalValues != null && metadata.AdditionalValues.ContainsKey(ShowForAttribute.AttributeKey))
			{
                ShowForAttribute attr = metadata.AdditionalValues[ShowForAttribute.AttributeKey] as ShowForAttribute;
				return attr.ShowForGrid;
			}
			return true;
		}

        public static bool ShowForFilter(this ModelMetadata metadata)
        {
            if (metadata.AdditionalValues != null && metadata.AdditionalValues.ContainsKey(ShowForAttribute.AttributeKey))
            {
                ShowForAttribute attr = metadata.AdditionalValues[ShowForAttribute.AttributeKey] as ShowForAttribute;
                return attr.ShowForFilter;
            }
            return false;
        }

        public static string FilterHint(this ModelMetadata metadata)
        {
            if (metadata.AdditionalValues != null && metadata.AdditionalValues.ContainsKey("FilterUIHint"))
            {
                FilterUIHintAttribute attr = metadata.AdditionalValues["FilterUIHint"] as FilterUIHintAttribute;
                if (!string.IsNullOrWhiteSpace(attr.FilterUIHint))
                    return string.Format("FilterTemplates/{0}", attr.FilterUIHint);
            }
            return metadata.TemplateHint;
        }

		public static IDictionary<string, object> UIParameters(this ModelMetadata metadata)
		{
			if (metadata.AdditionalValues != null && metadata.AdditionalValues.ContainsKey("UIHintParameters"))
			{
				return metadata.AdditionalValues["UIHintParameters"] as IDictionary<string, object>;
			}
			return null;
		}

		public static IDictionary<string, object> FilterUIParameters(this ModelMetadata metadata)
		{
			if (metadata.AdditionalValues != null && metadata.AdditionalValues.ContainsKey("UIHintParameters"))
			{
				return metadata.AdditionalValues["FilterUIHintParameters"] as IDictionary<string, object>;
			}
			return null;
		}

        public static IEnumerable<OperationAttribute> Operations(this ModelMetadata metadata)
        {
            return metadata.ModelType.GetCustomAttributes(typeof(OperationAttribute), true).Cast<OperationAttribute>();
        }

        public static IEnumerable<OperationAttribute> Operations(this Type type)
        {
            return type.GetCustomAttributes(typeof(OperationAttribute), true).Cast<OperationAttribute>();
        }
    }
}
